import 'dart:async';
import 'dart:io';

import 'package:chathouse/constant/app_constant.dart';
import 'package:chathouse/model/app_version.dart';
import 'package:chathouse/pages/client/account/client_account_page.dart';
import 'package:chathouse/pages/client/home/ClientHomePage.dart';
import 'package:chathouse/pages/client/search/client_hot_search_page.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../public/event_bus.dart';
import '../../push/chat_house_push.dart';
import '../../web_socket/web_socket_channel.dart';
import '../../widgets/app_update_widget.dart';
import '../../widgets/custom_floating_button.dart';
import '../../widgets/no_scaling_animation.dart';
import '../route_manager/root_route_manager.dart';
import 'msg/client_message_list_page.dart';
import 'order/client_order_page.dart';

///客户端主页--根容器页面
class ClientRootPage extends StatefulWidget {
  const ClientRootPage({Key? key}) : super(key: key);

  @override
  State<ClientRootPage> createState() => _ClientRootPageState();
}

class _ClientRootPageState extends State<ClientRootPage> {
  RootRouteController rootRouteController = RootRouteController(0, [
    const ClientHomePage(),
    const ClientOrderPage(),
    const ClientAccountPage(),
    const ClientHotSearchPage(),
    const ClientMessageListPage()
  ]);

  var noReadSericeNum = -1;
  Timer? timer;

  StreamSubscription? refreshSubscription;
  StreamSubscription? msgReadSubscription;

  @override
  void initState() {
    super.initState();
    AppConstant.rootController = rootRouteController;
    refreshSubscription = eventBus.on<ToMsgTabEvent>().listen((event) {
      if (!mounted) return;
      jumpPage(4);
    });
    loadMessageNum();
    timer = Timer.periodic(const Duration(seconds: 20), (timer) {
      loadMessageNum();
    });

    refreshSubscription = eventBus.on<UpdateMsgReadEvent>().listen((event) {
      if (!mounted) return;
      loadMessageNum();
    });

    refreshSubscription = eventBus.on<ToOrderEvent>().listen((event) {
      if (!mounted) return;
      rootRouteController.jumpToIndex(1);
      rootRouteController.cleanSubPageAndGoFirstPage(1);
      eventBus.fire(UpdateClientOrderEvent(2));
    });

    Apis.getAppVersion().then((value) async {
      LogUtil.d("getAppVersion后台返回数据：$value");
      var data = value?.data ?? {};
      var appModel = AppVersion.fromJson(data);
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String version = packageInfo.version;
      version = version.replaceAll(".", "");
      String newAppVersion = appModel.data?.appVersion ?? "0";
      bool isForcedUpdate = appModel.data?.isForcedUpdate ?? false;
      newAppVersion = newAppVersion.replaceAll(".", "");
      int newVersion = int.parse(newAppVersion);
      int currentVersion = int.parse(version);
      LogUtil.d("newAppVersion：$newVersion");
      LogUtil.d("currentVersion：$currentVersion");
      if (newVersion > currentVersion) {
        AppUpdateWidget.showUpdateDialog(
            appModel.data?.updateMsg ?? "", appModel.data?.appVersion ?? "",
            isForcedUpdate: isForcedUpdate);
      }
    }).catchError((error) {
      LogUtil.d("getAppVersion Error ${error}");
    });
  }

  loadMessageNum() {
    final params = {"kind": "0"};
    Apis.readNum(params).then((value) {
      print('loadMessageNum');
      print(value.toString());
      //  {"msg":"操作成功","code":200,"data":{"informReadNum":24,"projectReadNum":4,"seslistReadNum":2,"theReadNum":22}}
      if (value == null || value.data == null) {
        return;
      }
      // noReadSericeNum = value.data["data"]["informReadNum"];
      noReadSericeNum = value.data["data"]["seslistReadNum"];
      if (Platform.isAndroid) {
        _showBadge(noReadSericeNum);
      }else{
        ChatHousePush.instance.jpush.setBadge(noReadSericeNum);
      }
      setState(() {});
    }).onError((error, stackTrace) {});
  }

  Future<Null> _showBadge(int num) async {
    const badgeChannel = MethodChannel("chathouse.flutter");
    try {
      final result = await badgeChannel.invokeMethod('getBadge', {
        "badgeNum": num,
      });
    } on PlatformException catch (e) {
      if (kDebugMode) {
        LogUtil.d("_showBadge error: ${e.message}");
      }
    }
    // if(num == 0){
    //   FlutterAppBadger.removeBadge();
    // }else{
    //   FlutterAppBadger.updateBadgeCount(num);
    // }
  }

  @override
  void dispose() {
    rootRouteController.dispose();
    MyWebSocketChannel.instance.dispose();
    refreshSubscription?.cancel();
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        body: rootRouteController.getRootPageBody(),
        bottomNavigationBar: SafeArea(
          child: SizedBox(
            height: 75.w,
            child: Stack(
              children: <Widget>[
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    width: double.infinity,
                    decoration: const BoxDecoration(
                      // color: MyColors.green_69157608,
                      image: DecorationImage(
                          fit: BoxFit.fitWidth,
                          image: AssetImage(Res.img_bottom_bar_bg)),
                    ),
                    height: 75.w,
                    child: Flex(
                      direction: Axis.horizontal,
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: InkWell(
                              onTap: () {
                                jumpPage(0);
                              },
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  ImageUtils.image(Res.icon_awesome_home,
                                      width: 38.w, height: 30.w),
                                  const SizedBox(height: 5),
                                  Text(
                                    "首頁",
                                    style: getTextStyle(12.sp,
                                        color: MyColors.white),
                                  ),
                                ],
                              )),
                        ),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                              onTap: () {
                                jumpPage(1);
                              },
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  ImageUtils.image(Res.icon_order,
                                      width: 34.w, height: 34.w),
                                  const SizedBox(height: 3),
                                  Text("訂單",
                                      style: getTextStyle(12.sp,
                                          color: MyColors.white))
                                ],
                              )),
                        ),
                        Expanded(
                          flex: 1,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: const <Widget>[],
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                              //按下去的颜色 或者说是说中状态的颜色
                              highlightColor: MyColors.gary_139139139,
                              //点击时的水波纹颜色
                              splashColor: Colors.yellow,
                              onTap: () {
                                jumpPage(3);
                              },
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  ImageUtils.image(Res.icon_feather_search,
                                      width: 28.w, height: 28.w),
                                  const SizedBox(height: 6),
                                  Text("搜尋",
                                      style: getTextStyle(12.sp,
                                          color: MyColors.white)),
                                ],
                              )),
                        ),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                              onTap: () {
                                jumpPage(4);
                              },
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  ImageUtils.image(Res.icon_news,
                                      width: 38.w, height: 26.w),
                                  const SizedBox(height: 6),
                                  Text("訊息",
                                      style: getTextStyle(12.sp,
                                          color: MyColors.white))
                                ],
                              )),
                        )
                      ],
                    ),
                  ),
                ),
                Visibility(
                  visible: noReadSericeNum > 0,
                  child: Positioned(
                      right: 10.w,
                      top: 0,
                      child: Container(
                        alignment: Alignment.center,
                        width: 26.w,
                        height: 26.w,
                        decoration: const BoxDecoration(
                          color: Colors.red,
                          shape: BoxShape.circle,
                        ),
                        child: Text(
                          noReadSericeNum > 99 ? "99+" : "$noReadSericeNum",
                          style: getTextStyle(12.sp,
                              color: Colors.white, fontType: FontType.MID),
                        ),
                      )),
                )
              ],
            ),
          ),
        ),
        floatingActionButtonAnimator: NoScalingAnimation(),
        floatingActionButtonLocation: FloatingButtonCustomLocation(
            FloatingActionButtonLocation.centerDocked,
            // offsetY: Platform.isIOS ? 40.w : 0,
            offsetX: 0),
        floatingActionButton: SafeArea(
          child: Align(
              alignment: Alignment.bottomCenter,
              child: Padding(
                padding: const EdgeInsets.only(bottom: 2.0),
                child: GestureDetector(
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: MyColors.red_0000016, width: 1),
                      color: Colors.white,
                      shape: BoxShape.circle,
                    ),
                    // padding: const EdgeInsets.all(3),
                    child: Container(
                      margin: const EdgeInsets.only(top: 4),
                      width: 78.w,
                      height: 78.w,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          const SizedBox(height: 2),
                          ImageUtils.image(Res.login_logo,
                              width: 47.w, height: 52.w),
                          Text("賬戶",
                              style: getTextStyle(12.sp,
                                  color: MyColors.green_69157608))
                        ],
                      ),
                    ),
                  ),
                  onTap: () {
                    jumpPage(2);
                  },
                ),
              )),
        ));
  }

  void jumpPage(int index) {
    rootRouteController.jumpToIndex(index);
    rootRouteController.cleanSubPageAndGoFirstPage(index);
    if (index == 1) //點擊訂單，訂單頁面 選擇全部TabItem
    {
      eventBus.fire(UpdateClientOrderEvent(0));
    }
    if (index == 4) //點擊讯息
    {
      eventBus.fire(UpdateClientMessageEvent(0));
    }
  }
}
